package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/redis/go-redis/v9"
	"jd-mall/models/cache"
	"jd-mall/models/mysql"
	"strconv"
	"time"

	"jd-mall/jd_srv/internal/svc"
	"jd-mall/jd_srv/jd_srv"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShopInfoLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShopInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShopInfoLogic {
	return &ShopInfoLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ShopInfoLogic) ShopInfo(in *jd_srv.ShopInfoRequest) (*jd_srv.ShopInfoResponse, error) {
	// todo: add your logic here and delete this line
	var ShopInfo mysql.ShopList

	// 先从redis获取
	res, err := cache.RDB.Get(l.ctx, "shopInfoId:"+strconv.Itoa(int(in.ShopId))).Result()
	if res == "" || err == redis.Nil {
		// redis没有数据
		fmt.Println("mysql")
		mysql.DB.Table("shops").
			Select("shops.*,shop_images.*").
			Joins("left join shop_images on shop_images.id = shops.id").
			Where("shop_status = 1").
			Find(&ShopInfo)
		//存入redis
		marshal, _ := json.Marshal(&ShopInfo)
		cache.RDB.Set(l.ctx, "shopInfoId:"+strconv.Itoa(int(in.ShopId)), marshal, time.Hour)
	} else {
		// redis有数据
		fmt.Println("redis")
		_ = json.Unmarshal([]byte(res), &ShopInfo)
		fmt.Println(res)
		fmt.Println(ShopInfo)
	}

	return &jd_srv.ShopInfoResponse{
		Id:            int64(ShopInfo.Id),
		ShopImage:     ShopInfo.ShopImage,
		ShopName:      ShopInfo.ShopName,
		ShopDesc:      ShopInfo.ShopDesc,
		ShopPrice:     float32(ShopInfo.ShopPrice),
		ShopInventory: int64(ShopInfo.ShopInventory),
		ShopStatus:    int64(ShopInfo.ShopStatus),
	}, nil
}
